<template>
    <Modal :mask-closable="false"
            v-model="pictureVisible"
            :mask-closable="false"
            :title="!formItem.id ? '新增设备图片' : isDetail ? '查看设备图片' : '编辑设备图片'">
        <Form class="formList" ref="pictureForm" :model="formItem" :label-width="100" :rules="validateMalfunction" :disabled="isDetail">
            <FormItem label="设备名称：" prop="deviceName">
                <Select
                        v-model="formItem.deviceName"
                        filterable
                        clearable
                        :placeholder="`${$t('common.inputInfo')}`"
                        :remote-method="getSearchList"
                        :loading="searchLoading"
                >
                    <Option v-for="(item,index) of deviceList" :value="item.deviceName" :key="index">{{ item.deviceName }}</Option>
                </Select>
            </FormItem>
            <FormItem label="设备型号：" prop="specification">
                <Select
                        v-model="formItem.specification"
                        filterable
                        clearable
                        :placeholder="`${$t('common.inputInfo')}`"
                        :remote-method="getSpecificationList"
                        :loading="searchLoading"
                >
                    <Option v-for="(item,index) of specificationList" :value="item.specification" :key="index">{{ item.specification }}</Option>
                </Select>
            </FormItem>
            <FormItem label="设备图片：" prop="fileUrl">
                <Upload
                        ref="upload"
                        :show-upload-list="false"
                        :format="['jpg','jpeg','png', 'gif']"
                        :before-upload="handleBeforeUpload"
                        :on-format-error="handleFormatError"
                        type="drag"
                        action=""
                        style="display: inline-block;width:58px;">
                    <div style="width: 58px;height:58px;line-height: 58px;">
                        <img style="width: 100%;height:100%"
                             :src="util.filePathToUrl(formItem.filePath)" alt=""
                             v-if="util.filePathToUrl(formItem.filePath)">
                        <Icon type="ios-camera" size="20" else></Icon>
                    </div>
                </Upload>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="default"  @click="handleCancel">{{$t('common.Cancle')}}</Button>
            <Button type="primary" :loading="loading" v-show="!isDetail"  @click="handleOk">{{$t('maintenance.Confirmed')}}</Button>
        </div>
    </Modal>
</template>

<script>
    export default {
        name: "pictureModal",
        data() {
            return {
                id: '',
                searchLoading: false,
                isDetail: false,
                pictureVisible: false,
                loading: false,
                uploadAction: '',
                formItem: {
                    deviceName: '',
                    specification: '',
                    fileUrl: '',
                    filePath: '',
                    fileName: '',
                },
                validateMalfunction: {
                    deviceName: [
                        { required: true, message: '请输入使用工具', trigger: 'blur' }
                    ],
                    specification: [
                        { required: true, message: '请输入规格型号', trigger: 'blur' }
                    ],
                    fileUrl: [
                        { required: true, message: '请选择图片', trigger: 'blur' }
                    ],
                },
                deviceList: [],
                specificationList: []
            }
        },
        watch: {
            formItem: {
                handler(newValue) {
                    console.log(newValue)
                    this.formItem.fileUrl = newValue.fileUrl
                    this.formItem.filePath = newValue.filePath
                    this.formItem.fileName = newValue.fileName
                },
                immediate: true
            }
        },
        methods: {
            show(type, record, isDetail) {
                this.pictureVisible = true
                if (type === 'add') {
                    this.formItem.id = '';
                    this.formItem.deviceName = '';
                    this.formItem.specification = '';
                    this.formItem.fileUrl = '';
                    this.isDetail = false
                }else {
                    this.isDetail = isDetail || false
                    this.getDetail(record.id)
                }
            },
            async getDetail(id) {
                await this.axios({
                    method: 'get',
                    url: '/dms/dmsDevicePic/getDetail',
                    params: {
                        id
                    },
                }).then(res => {
                    
                    if (res.code == 200) {
                        this.formItem = res.data
                        this.formItem.id = res.data.id
                        this.formItem.fileUrl = res.data.fileUrl
                        this.formItem.fileName = res.data.fileName
                        this.formItem.filePath = res.data.filePath
                    }else {
                        this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                    }
                }).catch(() => {});
            },
            handleFormatError(file) {
                this.$Message.info("图片格式不正确,请上传正确的图片格式");
            },
            handleBeforeUpload(file) {
                console.log(file)
                let splic = file.name.split(".");
                if (
                    splic[splic.length - 1] == "png" ||
                    splic[splic.length - 1] == "jpg" ||
                    splic[splic.length - 1] == "gif" ||
                    splic[splic.length - 1] == "jpeg"
                ) {
                    let formData = new FormData();
                    formData.append("file", file);
                    formData.append("dir", 'device')
                    let config = {
                        headers: {
                            "Content-Type": "multipart/form-data"
                        }
                    };
                    this.axios({
                        method: 'post',
                        url: '/fileServer/upload',
                        data: formData,
                        config,
                    }).then(res => {
                        
                        if (res.code == 200) {
                            this.$nextTick(() => {
                                this.formItem.fileUrl = res.data.fileUrl
                                this.formItem.fileName = res.data.fileName
                                this.formItem.filePath = res.data.filepath
                            })
                        }else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}))
                        }
                    }).catch(() => {});
                    return false;
                }
            },
            getSearchList(query) {
                if (query !== '') {
                    this.searchLoading = true
                    this.axios({
                        method: 'get',
                        url: '/dms/dmsDevicePic/deviceList',
                        params: {
                            deviceName: query
                        }
                    }).then(res => {
                        if (res.code === 200) {
                            this.deviceList = res.data
                        } else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                        }
                    }).finally(() => {
                        this.searchLoading = false
                    })
                }else {
                    this.deviceList = []
                }
            },
            getSpecificationList(query) {
                if (query !== '') {
                    this.searchLoading = true
                    this.axios({
                        method: 'get',
                        url: '/dms/dmsDevicePic/deviceList',
                        params: {
                            deviceName: this.formItem.deviceName,
                            specification: query,
                        }
                    }).then(res => {
                        if (res.code === 200) {
                            this.specificationList = res.data
                        } else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                        }
                    }).finally(() => {
                        this.searchLoading = false
                    })
                }else {
                    this.specificationList = []
                }
            },
            handleOk() {
                let { id, deviceName, specification, fileUrl, fileName, filePath } = this.formItem
                this.$refs.pictureForm.validate((valid) => {
                    if (valid) {
                        this.loading = true
                        if (!this.formItem.id) {
                            let params = {
                                deviceName,
                                specification,
                                fileUrl,
                                fileName,
                                filePath
                            }
                            this.axios({
                                method: 'post',
                                url: '/dms/dmsDevicePic/add',
                                data: params
                            }).then(res => {
                                
                                if (res.code === 200) {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.success('新增成功！')
                                    this.$refs.pictureForm.resetFields();
                                    this.$emit('refresh')
                                }else {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.error(({content: res.msg, duration: 6, closable: true}))
                                    this.$refs.pictureForm.resetFields();
                                }
                            })
                        }else {
                            let params = {
                                id,
                                deviceName,
                                specification,
                                fileUrl,
                                fileName,
                                filePath
                            }
                            this.axios({
                                method: 'post',
                                url: '/dms/dmsDevicePic/edit',
                                data: params
                            }).then(res => {
                                
                                if (res.code === 200) {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.success('编辑成功！')
                                    this.$refs.pictureForm.resetFields();
                                    this.$emit('refresh')
                                }else {
                                    this.pictureVisible = false
                                    this.loading = false
                                    this.$Message.error(({content: res.msg, duration: 6, closable: true}))
                                    this.$refs.pictureForm.resetFields();
                                }
                            })
                        }
                    }
                })
            },
            handleCancel() {
                this.$refs.pictureForm.resetFields();
                this.pictureVisible = false
            }
        }
    }
</script>

<style scoped>
    .demo-upload-list {
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }

    .demo-upload-list img {
        width: 100%;
        height: 100%;
    }

    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }

    .ivu-icon {
        line-height: 58px;
    }
</style>
